package com.suemi.missile.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.suemi.missile.common.entity.ESDocument;
import com.suemi.missile.common.entity.Patent;
import com.suemi.missile.common.utils.Constants;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

public class MissileQuery {
  private HttpClient client = HttpClients.createDefault();

  private String prefix = "http://" + Constants.ES_HOST+":"+Constants.ES_PORT+"/missile/";

  public MissileQuery(String host, int port) {
    prefix ="http://"+ host+":"+port+"/missile/";
  }

  public QueryResult mqlQuery(String mql) throws URISyntaxException, IOException {

    QueryResult result = new QueryResult();

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add( new BasicNameValuePair( "mql", mql ));
    URI uri = new URI( prefix+"_mql?" + URLEncodedUtils.format( params, "utf-8" ));
    HttpUriRequest get = new HttpGet(uri);
    HttpResponse resp = client.execute(get);
    if(resp.getStatusLine().getStatusCode()!=200) return result;
    result.setSuccess(true);

    String jsonStr = IOUtils.toString(resp.getEntity().getContent());

    JSONObject json = JSON.parseObject(jsonStr);

    result.setTotal(json.getJSONObject("hits").getIntValue("total"));
    JSONArray hits = json.getJSONObject("hits").getJSONArray("hits");

    List<ESDocument> documents = new ArrayList<>();
    for(int i=0; i < hits.size(); ++i) {
      ESDocument document = new ESDocument();
      JSONObject tmp = hits.getJSONObject(i);
      document.setDocumentId(tmp.getString("_id"));
      Patent patent = new Patent();
      patent.fromJson(tmp.getJSONObject("_source"));
      document.setPatent(patent);
      documents.add(document);
    }

    result.setDocuments(documents);
    return result;
  }
}
